springboot2 解决跨域问题,跨域携带cookie |
您所在的位置:网站首页 › cookie 跨域设置 › springboot2 解决跨域问题,跨域携带cookie |
跨域问题,同源策略,CORS 这些介绍的文章网上搜下很多,不解释了。 我实际项目( springboot2 ) 中解决了跨域问题的方法:添加一个配置类 CorsConfig import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * @author: * @create: **/ @Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用 corsConfiguration.addAllowedHeader("*"); // 2允许任何头 corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等) corsConfiguration.setAllowCredentials(true);//支持安全证书。跨域携带cookie需要配置这个 corsConfiguration.setMaxAge(3600L);//预检请求的有效期,单位为秒。设置maxage,可以避免每次都发出预检请求 return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 return new CorsFilter(source); } }上述配置解决后端服务器跨域问题支持跨域携带cookie,同时前端也需要处理跨域请求。 参考 https://www.cnblogs.com/csguo/p/9597791.html 在此文基础上增加 支持跨域携带cookie 这里只是介绍了 全局配置解决springboot2后端跨域问题,网上还有通过 类、方法注解 实现更精确的跨域问题的方法 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |